import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;

public class UdpEchoServer {
    // 此处使用了 UDP 的两个 socket api
    // 一是，DatagramSocket ，用于发送和接收 UDP 数据报
    // 二是，DatagramPacket , 创建 UDP Socket 发送和接收的数据报

    private DatagramSocket socket = null;

    // 对于一个服务器来说，端口号要固定
    // 如果指定端口号被占用，绑定操作会报错
    // 同一个主机，一个端口号，同一时刻只能被一个进程绑定
    public UdpEchoServer(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }

    // 启动服务器的主逻辑
    public void start() throws IOException {
        System.out.println("服务器启动！");
        while(true){
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(requestPacket);
            String request = new String(requestPacket.getData(), 0, requestPacket.getLength());
            String response = process(request);
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),response.getBytes().length, requestPacket.getSocketAddress());
            socket.send(responsePacket);
            System.out.printf("[%s:%d] rep: %s, resp: %s\n", requestPacket.getAddress().toString(), requestPacket.getPort(),request, response );
        }


    }

    private String process(String request){
        return "I am here~" + request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer udpEchoServer = new UdpEchoServer(8090);
        udpEchoServer.start();
    }


}
